package com.huawei.hgip.paintgame.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;

import com.huawei.hgip.paintgame.activity.PaintSearchActivity;
import com.huawei.hgip.paintgame.m.data.UserProfile;

/**
 * 
 * @author Administrator
 *
 */
public class Communicate extends Thread {
	
	private Socket socket = null;
	//private String HOST = "10.138.20.58";	
//	private String HOST = "10.70.110.130";
//	private int PORT = 9999;
	private Handler mHandler;
	
	private PaintSearchActivity psActivity;
	
	public Communicate(PaintSearchActivity psActivity) {
		this.psActivity = psActivity;
		this.mHandler = psActivity.mHandler;
	}
	
	public void run(){
		//System.out.println("---in Communicate run(), thread id is: " + Thread.currentThread().getId());
		Message msg = new Message();
		msg.what = 1;
		while(true){
			long durTime = System.currentTimeMillis() - psActivity.lastTime;
			//System.out.println("durTime is : " + durTime);
			if(durTime > 2300 ){
				//System.out.println("--- start send msg!");
				mHandler.sendMessage(msg);
				//System.out.println("--- Communicate while break!");
				break;
			}
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		saveFile();
	}
	
	public void saveFile() {
		String filename = new Integer(PaintSearchActivity.userid).toString() + System.currentTimeMillis() + ".jpg";
		psActivity.votePicName = filename;
		System.out.println("---filename:" + filename);
		File dir = new File(PGUtil.ZZYY_HOME);
		if(!dir.exists()){
			dir.mkdir();
		}
		if (dir.canWrite()) {
			File newFile = new File(PGUtil.ZZYY_HOME + filename);
			FileOutputStream fos = null;
			try {
				newFile.createNewFile();
				if (newFile.exists() && newFile.canWrite()) {
					fos = new FileOutputStream(newFile);
					psActivity.mView.mBitmap.compress(Bitmap.CompressFormat.JPEG, 9, fos);
				}

				fos.flush();
				fos.close();
				//add by sunlian 获取当前源图片URI用于记录日志
				UserProfile.sourceUri = null;
				UserProfile.sourceUri = newFile.getPath();
				System.out.println("sourceUri:" + UserProfile.sourceUri);
				//end
				//System.out.println("---in socket111");
				//System.out.println("---socket host is : " + myView.myHOST);
				//System.out.println("---socket port is : " + myView.myPORT);
				socket = PGUtil.getSocket(PGUtil.BC_PIC_SEARCH);
				//System.out.println("socket ok");
				DataOutputStream ps = new DataOutputStream(
						socket.getOutputStream());
				DataInputStream ins = new DataInputStream(socket.getInputStream());

				sendFile(ps, newFile);
				//System.out.println("---start ps.flush");
				ps.flush();
				//System.out.println("---ps.flushed and input start");
				getResult(ins);//取得返回结果
				ins.close();
				socket.close();
				//System.out.println("---ok socket.close");

			} catch (IOException e) {
				psActivity.exceptionBackType = PGUtil.BC_SYS_ERR;
				e.printStackTrace();
			} finally {
				try {
					if (fos != null) {
						fos.flush();
						fos.close();
					}
					socket.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}
	
	public void getResult(InputStream ins) throws IOException{
		int result = readInteger(ins);
		System.out.println("in getResult, result is: " + result);
		switch (result){
		case PGUtil.BC_SYS_SUCCESS:
			psActivity.file1 = readAndSave(ins);
			//System.out.println("read and save file1 ok!");
			// file1 = "/sdcard/pic1294392436535.png";
			psActivity.file1ok = true;
//			//add by sunlian 获取当前结果1图片URI用于记录日志
//			UserProfile.result1Uri = null;
//			UserProfile.result1Uri = psActivity.file1;
//			//end
			psActivity.file2 = readAndSave(ins);
			//add by sunlian 获取当前结果1图片URI用于记录日志
			//end
			//System.out.println("read and save file2 ok!");
			// file2 = "/sdcard/pic1294130579532.png";
			psActivity.file2ok = true;
			//写日志
			UserProfile.result2Uri = null;
			UserProfile.result2Uri = psActivity.file2;
			UserProfile.userRecord();
			break;
//		case PGUtil.DRAW_SEARCH_OK:
//			psActivity.file1 = readAndSave(ins);
//			psActivity.file1ok = true;
//			psActivity.file2 = psActivity.file1;
//			psActivity.file2ok = true;
//			break;		
		case PGUtil.BC_SYS_ERR:
			psActivity.exceptionBackType = PGUtil.BC_SYS_ERR;
			break;		
//		case PGUtil.NO_SUIT_RESULT:
//			psActivity.exceptionBackType = PGUtil.NO_SUIT_RESULT;
//			break;
		}
	}
	
	


	/**
	 * 发送文件。文件大小不能大于 {@link Integer#MAX_VALUE}
	 * 
	 * @param hostname
	 *            接收端主机名或 IP 地址
	 * @param port
	 *            接收端端口号
	 * @param filepath
	 *            文件路径
	 * 
	 * @throws IOException
	 *             如果读取文件或发送失败
	 */
	public void sendFile(OutputStream os, File file) throws IOException {
		//System.out.println("in send File");
		FileInputStream is = new FileInputStream(file);
		//System.out.println("is ok!");

		try {
			int length = (int) file.length();
			//System.out.println("send file is: " + file.getName() + " length: " + length);
			// 发送文件名和文件内容
			//os.write(PGUtil.i2b(psActivity.currentService));//write service type first!
			writeFileName(file, os);
			writeFileContent(is, os, length);
		} finally {
			// os.close();
			is.close();
		}
	}

	// 输出文件内容
	private void writeFileContent(InputStream is, OutputStream os, int length)
			throws IOException {
		// 输出文件长度
		os.write(PGUtil.i2b(length));

		// 输出文件内容
		byte[] buffer = new byte[1024];
		int size;
		while ((size = is.read(buffer)) != -1) {
			os.write(buffer, 0, size);
		}
	}

	// 输出文件名
	private void writeFileName(File file, OutputStream os) throws IOException {
		PGUtil.writeStringWithLength(file.getName(), os);
	}

	// 从流中读取内容并保存
	private String readAndSave(InputStream is) throws IOException {
		String filename = PGUtil.ZZYY_HOME + getFileName(is);
		int file_len = readInteger(is);
		//System.out.println("received file is: " + filename + "length is : " + file_len);

		readAndSave0(is, filename, file_len);

		//System.out.println("file save success: " + file_len + "bytes");
		return filename;

	}

	private void readAndSave0(InputStream is, String path, int file_len)
			throws IOException {
		FileOutputStream os = getFileOS(path);
		readAndWrite(is, os, file_len);
		os.close();
	}

	// 边读边写，直到读取 size 个字节
	private void readAndWrite(InputStream is, FileOutputStream os, int size)
			throws IOException {
		int bufsize = 4096;
		byte[] buffer = new byte[bufsize];
		int count = 0;
		while (count < size) {
			if ((count + bufsize) >= size) {// 最后一个buff
				buffer = new byte[size - count];
			}
			int n = is.read(buffer);
			// 这里没有考虑 n = -1 的情况
			os.write(buffer, 0, n);
			//System.out.println("n is: " + n);
			count += n;
			//System.out.println("count is: " + count);
		}
	}

	// 读取文件名
	private String getFileName(InputStream is) throws IOException {
		int name_len = readInteger(is);
		//System.out.println("name_len is: " + name_len);
		byte[] result = new byte[name_len];
		is.read(result);
		return new String(result);
	}

	// 读取一个数字
	private int readInteger(InputStream is) throws IOException {
		byte[] bytes = new byte[4];
		is.read(bytes);
		return PGUtil.b2i(bytes);
	}

	// 创建文件并返回输出流
	private FileOutputStream getFileOS(String path) throws IOException {
		File file = new File(path);
		if (!file.exists()) {
			file.createNewFile();
		}

		return new FileOutputStream(file);
	}

}